/**
 * @author: Meloa
 * @create: 2020-12-11 15:32
 **/
package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SubMailUtils {
    @Autowired
    Gson gson;

    public static String subMailUtils(String phone, String code) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // api 地址
        String url = "https://api.mysubmail.com/message/xsend";
        // 需要使用 POST 请求
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonParam = new JSONObject();
        // 创建的 APPID
        jsonParam.put("appid", "58732");
        // 创建的 APPID 的 APPKEY
        jsonParam.put("signature", "f7c84c072492880ffeb6441ff50d0c11");
        // 你的模板编号，见 https://www.mysubmail.com/chs/documents/developer/MmSw12
        jsonParam.put("project", "M3Qh22");
        // 接收人手机号
        jsonParam.put("to", phone);
        JSONObject vars = new JSONObject();
        // 模板变量
        vars.put("code", code);
        jsonParam.put("vars", vars.toJSONString());
        StringEntity entity = new StringEntity(jsonParam.toJSONString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        // 响应体
        HttpResponse resp = httpclient.execute(httpPost);
        String respContent = null;
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        return respContent;


    }

}